package day52.basic.service.impl;

import com.alibaba.fastjson.JSONObject;
import day52.basic.commonenum.ErrorCode;
import day52.basic.constants.Constant;
import day52.basic.domain.dto.WechaBinderDto;
import day52.basic.domain.dto.WechatRegisterDto;
import day52.basic.domain.dto.LoginDto;
import day52.basic.exception.CustomException;
import day52.basic.jwt.JwtUtils;
import day52.basic.jwt.RsaUtils;
import day52.basic.jwt.UserInfo;
import day52.basic.service.ILoginService;
import day52.basic.util.*;
import day52.system.domain.Menu;
import day52.system.mapper.MenuMapper;
import day52.system.mapper.PermissionMapper;
import day52.user.domain.Logininfo;
import day52.user.domain.User;
import day52.user.domain.Wxuser;
import day52.user.mapper.LogininfoMapper;
import day52.user.mapper.UserMapper;
import day52.user.mapper.WxuserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Value("${jwt.rsa.pri}")// SPEL表达式读取配置文件中的值
    private String jwtRsaPrivate;


    @Override
    public AjaxResult loginByAccount(LoginDto dto) {
        //通过填写的账号查询是否有这个用户(username or phone or email)
        Logininfo lf = logininfoMapper.findByUserName(dto.getAccount(),dto.getType());
        if(lf == null){
            throw new CustomException(ErrorCode.ACCOUNT_NOT_FOUND.getCode());
        }
        //校验密码(把用户填写的用查询出来的salt加密和数据库加密后的密码进行比对)
        String password = MD5Utils.encrypByMd5(dto.getPassword() + lf.getSalt());
        if(!password.equals(lf.getPassword())){
            throw new CustomException(ErrorCode.PASSWORD_ERROR.getCode());
        }
        //存redis(key:uuid 值：logininfo)
        //HashMap<String, Object> hm = loginWithoutPassword(lf);
        //return AjaxResult.me().setResultObj(hm);
        return AjaxResult.me().setResultObj(loginSuccessHandler(lf));
    }

    @Override
    public AjaxResult loginByWechat(Map<String, String> map) {
        //参数校验
        String code = map.get("code");
        if(code == null){
            throw new CustomException(ErrorCode.WECHAT_ERROR.getCode());
        }
        //获取accessToken
        //获取getTokenUrl
        String getTokenUrl = Constant.WxConstants.GET_TOKEN_URL
                .replace("APPID",Constant.WxConstants.APPID)
                .replace("SECRET",Constant.WxConstants.SECRET)
                .replace("CODE",code);
        //后端发送get请求获取accessToken
        String jsonStr = HttpClientUtils.httpGet(getTokenUrl);
        //将返回的jsonStr字符串对象转成json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        //从json对象中获取accessToken和openid
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        //判断wxuser中是否存在该对象
        Wxuser wxuser = wxuserMapper.findByOpenid(openid);
        //不存在则注册并绑定
        if(wxuser == null){
            String binderUrl = "?accessToken="+access_token+"&openId="+openid;
            return AjaxResult.me().setResultObj(binderUrl).setSuccess(false);
        }else {
            //从wxuser中获取userId
            Long userId = wxuser.getUserId();
            //查询到logininfo信息进行登陆
            Logininfo lf = userMapper.findLogininfoByUserId(userId);
            //免密登陆
            //HashMap<String, Object> hm = loginWithoutPassword(lf);
            //return AjaxResult.me().setResultObj(hm);
            return AjaxResult.me().setResultObj(loginSuccessHandler(lf));
        }
    }

    /**
     * 微信注册
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public AjaxResult registerByWechat(WechatRegisterDto dto) {
        //查询手机号是否正确
        String phone = dto.getPhone();
        Boolean isPhone = PhoneCheck.isMobile(phone);
        if(!isPhone){
            throw new CustomException(ErrorCode.PASSWORD_REPEAT.getCode());
        }
        //查询两次密码是否一致
        if(!dto.getPassword().equals(dto.getConfirmPassword())){
            throw new CustomException(ErrorCode.PASSWORDS_INCONSISTENT.getCode());
        }
        //用传递来的token和openid获取该用户微信的基本信息
        //获取请求地址
        Wxuser wxuser = getWxuser(dto.getAccess_token(), dto.getOpenid());
        //用户未注册
        //封装要保存的对象logininfo user wxuser
        String salt = StrUtils.getComplexRandomString(32);
        String password = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        //封装好了loginInfo对象
        Logininfo lf = initLoginInfo(dto, salt, password);
        logininfoMapper.add(lf);
        //封装user并保存
        User user = loginInfo2User(lf);
        userMapper.add(user);
        //封装wxuser对象
        wxuser.setUserId(user.getId());
        wxuserMapper.add(wxuser);
        //免密登录
        //HashMap<String, Object> hm = loginWithoutPassword(lf);
        //return AjaxResult.me().setResultObj(hm);
        return AjaxResult.me().setResultObj(loginSuccessHandler(lf));
    }

    /**
     * 微信绑定
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public AjaxResult binderByWechat(WechaBinderDto dto) {
        //查询手机号是否正确
        Boolean isPhone = PhoneCheck.isMobile(dto.getPhone());
        if(!isPhone){
            throw new CustomException(ErrorCode.PASSWORD_REPEAT.getCode());
        }
        //查询用户是否已经注册
        User user = userMapper.findByPhone(dto.getPhone());
        if (user == null){
            //没注册，则要求输入密码进行注册
            return AjaxResult.me().setSuccess(false);
        }
        //已经注册
        Wxuser wxuser = getWxuser(dto.getAccess_token(), dto.getOpenid());
        //绑定微信
        wxuser.setUserId(user.getId());
        wxuserMapper.add(wxuser);
        //通过user找到logininfo
        Logininfo lf = logininfoMapper.findOne(user.getLogininfoId());
        //免密登录
        //HashMap<String, Object> hm = loginWithoutPassword(lf);
        //return AjaxResult.me().setResultObj(hm);
        return AjaxResult.me().setResultObj(loginSuccessHandler(lf));
    }

    /**
     * 免密登陆，无状态token方式
     * @param lf
     * @return
     */
    private HashMap<String, Object> loginWithoutPassword(Logininfo lf) {
        //存redis(key:uuid 值：logininfo)
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token, lf, 30, TimeUnit.MINUTES);
        //组装数据返回给前端(map组装数据)
        HashMap<String, Object> hm = new HashMap<>();
        hm.put("token", token);
        //处理logininfo
        lf.setPassword(null);
        lf.setSalt(null);
        lf.setDisable(null);
        hm.put("logininfo", lf);
        return hm;
    }

    /**
     * 从tx获取wxuser基本信息转换成wxusr对象
     * @param access_token
     * @param openid
     * @return
     */
    private Wxuser getWxuser(String access_token, String openid) {
        //用传递来的token和openid获取该用户微信的基本信息
        //获取请求地址
        String url = Constant.WxConstants.GET_USER_URL
                .replace("ACCESS_TOKEN", access_token)
                .replace("OPENID", openid);
        //发送请求
        String jsonStr = HttpClientUtils.httpGet(url);
        //从tx获取wxuser基本信息
        return JSONObject.parseObject(jsonStr, Wxuser.class);
    }

    /**
     * 封装logininfo
     * @param dto
     * @param salt
     * @param password
     * @return
     */
    private Logininfo initLoginInfo(WechatRegisterDto dto, String salt, String password) {
        Logininfo lf = new Logininfo();
        lf.setUsername(dto.getPhone());
        lf.setPhone(dto.getPhone());
        lf.setSalt(salt);
        lf.setPassword(password);
        lf.setType(1);
        lf.setDisable(1);
        return lf;
    }

    /**
     * Logininfo对象转User
     * @param lf
     * @return
     */
    private User loginInfo2User(Logininfo lf){
        User user = new User();
        //bean拷贝，把相同字段的值拷贝到另一个对象的相同字段去
        BeanUtils.copyProperties(lf,user);
        user.setState(1);
        user.setCreateTime(new Date());
        user.setLogininfoId(lf.getId());
        return user;
    }

    /**
     * 登录成功处理
     * @param logininfo
     * @return
     */
    private Map<String, Object> loginSuccessHandler(Logininfo logininfo) {
        UserInfo userInfo = new UserInfo();
        Map<String, Object> map = new HashMap<>();
        userInfo.setLogininfo(logininfo);
        //判断当前用户是主站还是后端管理系统
        if(logininfo.getType() == 1){
            //单纯返回个人信息
            try {
                PrivateKey privateKey = RsaUtils
                        .getPrivateKey(FileCopyUtils
                                .copyToByteArray(this.getClass().getClassLoader().getResourceAsStream(jwtRsaPrivate)));
                //加密得到token
                String token = JwtUtils.generateTokenExpireInMinutes(userInfo, privateKey, 60*24);
                logininfo.setPassword(null);
                logininfo.setSalt(null);
                map.put("logininfo",logininfo);
                map.put("token",token);
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            } catch (InvalidKeySpecException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }else{
            //如果是后端，返回个人信息+权限信息
            List<String> sns = permissionMapper.findPermissionByLoginInfoId(logininfo.getId());
            List<Menu> menus = menuMapper.findMenuByLoginInfoId(logininfo.getId());
            userInfo.setPermissions(sns);
            userInfo.setMenus(menus);
            try {
                //获取私钥
                PrivateKey privateKey = RsaUtils
                        .getPrivateKey(FileCopyUtils
                                .copyToByteArray(this.getClass().getClassLoader().getResourceAsStream(jwtRsaPrivate)));
                //加密得到token
                String token = JwtUtils.generateTokenExpireInMinutes(userInfo, privateKey, 60*24);
                logininfo.setPassword(null);
                logininfo.setSalt(null);
                map.put("logininfo",logininfo);
                map.put("token",token);
                map.put("permissions",sns);
                map.put("menus",menus);
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            } catch (InvalidKeySpecException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return map;
    }
}
